/***************************************************************************
 * 文件名:EtCodingSchemes.java<br>
 * 版本: <br>
 * 描述: <br>
 * 版权所有: <br>
 * //////////////////////////////////////////////////////// <br>
 * 创建者: robo<br>
 * 创建日期: 2010-11-9 <br>
 * 修改者: <br>
 * 修改日期: <br>
 * 修改说明: <br>
 **************************************************************************/
package com.sunwayhorizo.health.ets.base.service;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.ejb.Stateless;
import javax.persistence.Query;

import org.apache.commons.lang.StringUtils;
import org.jboss.seam.Component;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.log.Log;

import com.sunwayhorizo.health.business.dto.ResultsDTO;
import com.sunwayhorizo.health.common.ListUtil;
import com.sunwayhorizo.health.common.StrUtil;
import com.sunwayhorizo.health.ets.base.common.BaseDao;
import com.sunwayhorizo.health.ets.base.persistent.EtCodingSchemes;
import com.sunwayhorizo.health.ets.base.persistent.EtModels;
import com.sunwayhorizo.health.ets.base.persistent.EtVersions;
import com.sunwayhorizo.health.ets.dto.EtCodingSchemesDTO;
import com.sunwayhorizo.health.ets.dto.EtModelsDTO;

@Name("EtCodingSchemesManager")
@Stateless
@SuppressWarnings("unchecked")
public class EtCodingSchemesManager extends BaseDao implements
		EtCodingSchemesManagerLocal {

	@Logger
	Log log;

	public List<com.sunwayhorizo.health.ets.base.persistent.EtCodingSchemes> findEtCodingSchemesAll()
			throws Exception {
		return entityManager2.createNamedQuery(" EtCodingSchemes.findAll ")
				.getResultList();
	}

	public ResultsDTO findEtCodingSchemes(int currentPage, int pageSize,
			String name, String code) throws Exception {
		ResultsDTO model = new ResultsDTO(currentPage, pageSize);
		String jpql = "select o from EtCodingSchemes o where 1=1 ";
		Query query = getJpql(name, code, jpql);
		query.setFirstResult(model.getBeginIndex());
		query.setMaxResults(model.getPageSize());
		List<EtCodingSchemes> list = query.getResultList();

		List<EtCodingSchemesDTO> returnList = new ArrayList<EtCodingSchemesDTO>();
		if (list != null && list.size() > 0) {
			for (EtCodingSchemes ecs : list) {
				EtCodingSchemesDTO dto = convertEtCodingSchemesDTO(ecs);
				returnList.add(dto);
			}
		}

		model.setObject(returnList);
		model.setTotalRecords(findEtCodingSchemesCount(name, code));
		model.setResultFlag(true);
		model.setResultDesc("查询成功");
		return model;
	}

	public ResultsDTO findEtModelsList() throws Exception {
		ResultsDTO model = new ResultsDTO(0, 0);
		List<EtModelsDTO> returnList = new ArrayList<EtModelsDTO>();
		EtModelsManagerLocal evmLocal = (EtModelsManagerLocal) Component
				.getInstance("EtModelsManager");
		dto = evmLocal.findEtModelsList(0, 0, null);
		if (null != dto.getObject()) {
			returnList = (List<EtModelsDTO>) dto.getObject();
			for (EtModelsDTO em : returnList) {
				List<EtCodingSchemesDTO> csList = new ArrayList<EtCodingSchemesDTO>();
				if (null != em && StringUtils.isNotEmpty(em.getModelName())) {
					String jpql = " select ecs from EtCodingSchemes ecs where ecs.etModels.modelName='"
							+ em.getModelName() + "'";
					List<EtCodingSchemes> list = entityManager2.createQuery(
							jpql).getResultList();
					for (EtCodingSchemes ecs : list) {
						csList.add(convertEtCodingSchemesDTO(ecs));
					}
					em.setChildren(csList);
				}
			}
		}
		model.setObject(returnList);
		model.setResultFlag(true);
		model.setResultDesc("查询成功");
		return model;
	}

	@SuppressWarnings("unused")
	private EtModelsDTO convertEtModelsDTO(EtModels ecs) {
		EtModelsDTO dto = new EtModelsDTO();
		dto.setModelName(ecs.getModelName());
		dto.setCacheCodeBase(ecs.getCacheCodeBase());
		List<EtCodingSchemesDTO> lst = new ArrayList<EtCodingSchemesDTO>();
		if (null != ecs.getChildren() && ecs.getChildren().size() > 0) {
			for (EtCodingSchemes ecPo : ecs.getChildren()) {
				lst.add(convertEtCodingSchemesDTO(ecPo));
			}
		}
		dto.setChildren(lst);
		dto.setClientCodeBase(ecs.getClientCodeBase());
		dto.setCreatedBy(ecs.getCreatedBy());
		dto.setCreationDate(ecs.getCreationDate());
		dto.setImporterCodeBase(ecs.getImporterCodeBase());
		dto.setLastUpdateDate(ecs.getLastUpdateDate());
		dto.setLastUpdatedBy(ecs.getLastUpdatedBy());
		dto.setLastUpdateLogin(ecs.getLastUpdateLogin());
		dto.setLoaderCodeBase(ecs.getLoaderCodeBase());
		dto.setModelDesc(ecs.getModelDesc());
		return dto;
	}

	private EtCodingSchemesDTO convertEtCodingSchemesDTO(EtCodingSchemes ecs) {
		EtCodingSchemesDTO dto = new EtCodingSchemesDTO();
		dto.setCodingschemeChName(ecs.getCodingschemeChName());
		dto.setCodingschemeDesc(ecs.getCodingschemeDesc());
		dto.setCodingschemeEnName(ecs.getCodingschemeEnName());
		dto.setCodingschemeId(ecs.getCodingschemeId());
		dto.setCodingschemeOid(ecs.getCodingschemeOid());
		dto.setCreatedBy(ecs.getCreatedBy());
		dto.setCreatedByName(ecs.getCreatedByName());
		dto.setCreationDate(ecs.getCreationDate());
		dto.setEditableFlag(ecs.getEditableFlag());
		dto.setLastUpdateDate(ecs.getLastUpdateDate());
		dto.setLastUpdatedBy(ecs.getLastUpdatedBy());
		dto.setLastUpdatedByName(ecs.getLastUpdatedByName());
		dto.setLastUpdateLogin(ecs.getLastUpdateLogin());
		dto.setModelName(ecs.getEtModels().getModelName());
		dto.setModelDesc(ecs.getEtModels().getModelDesc());
		dto.setComplexable(ecs.getComplexable());
		return dto;
	}

	public int findEtCodingSchemesCount(String name, String code)
			throws Exception {
		String jpql = "select count(o.codingschemeId) from  EtCodingSchemes o where 1=1 ";
		Query query = getJpql(name, code, jpql);
		List<Long> list = query.getResultList();
		if (list != null && list.size() > 0) {
			return list.get(0).intValue();
		}
		return 0;
	}

	private Query getJpql(String name, String code, String jpql) {
		if (name != null && !name.equals("")) {
			jpql += " and  o.codingschemeChName  like '%" + name + "%' ";
		}
		if (code != null && !code.equals("")) {
			jpql += " and o.codingschemeEnName like '%" + code + "%'  ";
		}
		Query query = entityManager2.createQuery(jpql);
		return query;
	}

	public ResultsDTO newEtCodingSchemes(EtCodingSchemesDTO dto)
			throws Exception {
		ResultsDTO model = new ResultsDTO();
		if (dto != null) {
			EtCodingSchemes ecs = new EtCodingSchemes();
			if (StrUtil.isNotEmpty(dto.getModelName())) {
				EtModels etModels = new EtModels();
				etModels.setModelName(dto.getModelName());
				ecs.setEtModels(etModels);
			}
			ecs.setCodingschemeChName(dto.getCodingschemeChName());
			ecs.setCodingschemeDesc(dto.getCodingschemeDesc());
			ecs.setCodingschemeEnName(dto.getCodingschemeEnName());
			ecs.setCodingschemeOid(dto.getCodingschemeOid());
			ecs.setEditableFlag(dto.getEditableFlag());
			ecs.setComplexable(dto.getComplexable());
			// 从当前session取
			ecs.setCreatedBy(1l);
			ecs.setCreatedByName("");
			ecs.setCreationDate(new Timestamp(new Date().getTime()));
			ecs.setLastUpdateDate(new Timestamp(new Date().getTime()));
			ecs.setLastUpdatedBy(1l);
			ecs.setLastUpdatedByName("");
			ecs.setLastUpdateLogin(1l);
			entityManager2.persist(ecs);
			model.setObject(ecs.getCodingschemeId());
		}

		model.setResultDesc("成功");
		model.setResultFlag(true);
		return model;
	}

	public ResultsDTO updateEtCodingSchemes(EtCodingSchemesDTO dto)
			throws Exception {
		ResultsDTO model = new ResultsDTO();
		if (dto != null) {
			EtCodingSchemes ecs = entityManager2.find(EtCodingSchemes.class,
					dto.getCodingschemeId());
			if (ecs != null) {
				ecs.setCodingschemeChName(dto.getCodingschemeChName());
				ecs.setCodingschemeDesc(dto.getCodingschemeDesc());
				ecs.setCodingschemeEnName(dto.getCodingschemeEnName());
				ecs.setCodingschemeOid(dto.getCodingschemeOid());
				ecs.setEditableFlag(dto.getEditableFlag());
				ecs.setComplexable(dto.getComplexable());
				// 从当前session取
				ecs.setCreatedBy(1l);
				ecs.setCreatedByName("");
				ecs.setCreationDate(new Timestamp(new Date().getTime()));
				ecs.setLastUpdateDate(new Timestamp(new Date().getTime()));
				ecs.setLastUpdatedBy(1l);
				ecs.setLastUpdatedByName("");
				ecs.setLastUpdateLogin(1l);
				entityManager2.merge(ecs);

				model.setResultDesc("成功");
				model.setResultFlag(true);
			} else {
				model.setResultFlag(false);
				model.setResultDesc("操作失败");
				log.info("更新失败");
			}
		}
		return model;
	}

	/**
	 * 检查唯一性
	 * 
	 * @param dto
	 * @return
	 * @throws Exception
	 */
	public ResultsDTO checkUnique(EtCodingSchemesDTO dto) throws Exception {
		ResultsDTO model = new ResultsDTO();
		List<String> rtObj = new ArrayList<String>();
		if (null != dto) {
			String fieldName;
			if (StrUtil.isNotEmpty(dto.getCodingschemeEnName())) {
				String jpql = "select o from EtCodingSchemes o where o.codingschemeEnName ='"
						+ dto.getCodingschemeEnName() + "'";
				Query query = getJpql(null, null, jpql);
				fieldName = "codingschemeEnName";
				if (null != query && ListUtil.isNotEmpty(query.getResultList())) {
					rtObj.add(fieldName + "_" + query.getResultList().size());
				} else {
					rtObj.add(fieldName + "_0");
				}
			}
			if (StrUtil.isNotEmpty(dto.getCodingschemeOid())) {
				String jpql = "select o from EtCodingSchemes o where o.codingschemeOid ='"
						+ dto.getCodingschemeOid() + "'";
				Query query = getJpql(null, null, jpql);
				fieldName = "codingschemeOid";
				if (null != query && ListUtil.isNotEmpty(query.getResultList())) {
					rtObj.add(fieldName + "_" + query.getResultList().size());
				} else {
					rtObj.add(fieldName + "_0");
				}
			}
			if (StrUtil.isNotEmpty(dto.getCodingschemeChName())) {
				String jpql = "select o from EtCodingSchemes o where o.codingschemeChName ='"
						+ dto.getCodingschemeChName() + "'";
				Query query = getJpql(null, null, jpql);
				fieldName = "codingschemeChName";
				if (null != query && ListUtil.isNotEmpty(query.getResultList())) {
					rtObj.add(fieldName + "_" + query.getResultList().size());
				} else {
					rtObj.add(fieldName + "_0");
				}
			}
			model.setResultFlag(true);
			model.setResultDesc("术语字典唯一性验证成功");
		} else {
			model.setResultFlag(false);
			model.setResultDesc("术语字典唯一性验证失败");
		}
		model.setObject(rtObj);
		return model;
	}

	@SuppressWarnings("rawtypes")
	public ResultsDTO delEtCodingSchemes(List ids) throws Exception {
		ResultsDTO resultsDTO = new ResultsDTO();
		if (ids != null && ids.size() > 0) {
			EtVersionsManagerLocal evmLocal = (EtVersionsManagerLocal) Component
					.getInstance("EtVersionsManager");
			for (int i = 0; i < ids.size(); i++) {
				String id = (String) ids.get(i);
				@SuppressWarnings("unused")
				EtCodingSchemesDTO dto = new EtCodingSchemesDTO();
				boolean bo = evmLocal.findEtVersionsByCodingSchemesId(id);
				if (bo) {
					resultsDTO.setResultDesc("不能删除术语分类，分类下已经有术语版本");
					resultsDTO.setResultFlag(false);
				} else {
					EtCodingSchemes ecs = entityManager2.find(
							EtCodingSchemes.class, id);
					if (null != ecs
							&& StrUtil.isNotEmpty(ecs.getCodingschemeId())) {
						entityManager2.remove(ecs);
					}
					resultsDTO.setResultDesc("删除成功");
					resultsDTO.setResultFlag(true);
				}
			}
		}
		return resultsDTO;
	}

	public List<EtVersions> getVersion(String name) throws Exception {
		String jpql = "select o from EtVersions o,EtCodingSchemes ets where o.etCodingSchemes= ets.codingschemeId ";
		if (name != null && !name.equals("")) {
			jpql += " and ets.codingschemeChName =: name ";
		}
		Query query = entityManager2.createQuery(jpql);
		if (name != null && !name.equals("")) {
			query.setParameter("name", name);
		}

		return query.getResultList();
	}

	public ResultsDTO findEtModelsAndEtCodingSchemesTree() throws Exception {
		ResultsDTO resultsDTO = new ResultsDTO();
		List<EtModels> modelsList = entityManager2.createNamedQuery(
				"EtModels.findAll").getResultList();

		StringBuilder sb = new StringBuilder(
				"select o from EtCodingSchemes o , EtModels etm where etm.modelName=o.etModels.modelName");
		List<EtCodingSchemes> codingSchemesList = entityManager2.createQuery(
				sb.toString()).getResultList();
		EtModelsManagerLocal local = (EtModelsManagerLocal) Component
				.getInstance("EtModelsManager");

		List<EtModelsDTO> returnList = new ArrayList<EtModelsDTO>();
		if (modelsList != null && modelsList.size() > 0) {
			for (EtModels etModels : modelsList) {
				String modelName = etModels.getModelName();
				EtModelsDTO mDto = new EtModelsDTO();
				mDto = local.convertEtModelsDTO(etModels);
				List<EtCodingSchemesDTO> children = new ArrayList<EtCodingSchemesDTO>();
				if (codingSchemesList != null && codingSchemesList.size() > 0) {
					for (EtCodingSchemes ecs : codingSchemesList) {
						if (modelName.equals(ecs.getEtModels().getModelName())) {
							EtCodingSchemesDTO dto = convertEtCodingSchemesDTO(ecs);
							children.add(dto);
						}
					}
				}
				mDto.setChildren(children);
				returnList.add(mDto);
			}
		}
		resultsDTO.setResultFlag(true);
		resultsDTO.setObject(returnList);
		resultsDTO.setResultDesc("查询成功");
		return resultsDTO;
	}

	public boolean isEditable() throws Exception {
		return true;
	}

}
